<?php

/**
 * 表单验证
 * @subpackage application/libraries
 * @ $this->my_validation->checkFormData()
 */
if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );

class Validation
{
	private $CI;

	public function __construct()
    {
		$this->CI = & get_instance();
	}

    public function checkFormData($formdata,$formName)
    {

        $error_code = $this->CI->config->item('error_code');

        if( empty($formName)) throw new Exception($error_code[2001],2001);
        $validation  = $this->CI->config->item('validation');
        
        if( isset($validation[$formName]) )
        {
            $code = 0;
            $checkedData = array(); 

            foreach($validation[$formName] as $k => $v)
            {
                if(!isset($v['requirement'])) continue;
                $regular_arr = explode('|',$v['requirement']);
                foreach($regular_arr as $regular)
                {
                    if($regular == 'required')
                    {
                        if(!isset($formdata[$k]) || $formdata[$k] == '' || $formdata[$k] === null)
                            throw new Exception(sprintf($error_code[2003],$v['name']),2003);
                    }

                    else if(stristr($regular,'length'))
                    {
                        preg_match('/(\d+|\*)-(\d+|\*)/', $regular, $matches);
                        if( !@$matches[0] ) throw new Exception($error_code[2007],2007);

                        $size = explode('-',$matches[0]);
                        if ( isset($size[0]) && isset($size[1]) )
                        {
                            $min = $size[0];
                            $max = $size[1];
                        }
                        else
                        {
                            throw new Exception($error_code[2007],2007);
                        }

                        //系统编码
                        $charset = $this->CI->config->item('charset');
                        $length = mb_strlen(@$formdata[$k],$charset);
                    
                        if($min != '*' && $length < $min)
                        {
                            throw new Exception(sprintf($error_code[2008],$v['name'],$min),2008);
                        }
                        if($max != '*' && $length > $max)
                        {
                            throw new Exception(sprintf($error_code[2009],$v['name'],$max),2009);
                        }
                    }
                    else if($regular == 'illegal')
                    {
                        $this->CI->load->helper('security');
                        /*
                        if ( @$formdata[$k] != xss_clean(@$formdata[$k]) )
                            throw new Exception("{$v['name']}中含有非法字符",$code);
                        */
                        $formdata[$k] = xss_clean($formdata[$k],FALSE,TRUE);
                    }
                    else if($regular == 'email')
                    {
                        if ( !preg_match('/^[\.\-_A-Za-z0-9]+@([_A-Za-z0-9]+\.)+[A-Za-z0-9]{2,3}$/', @$formdata[$k]) )
                            throw new Exception(sprintf($error_code[2010],$v['name']),2010);
                    }
                    else if($regular == 'telephone')
                    {
                        if ( strlen( @$formdata[$k] ) != 11 )
                            throw new Exception(sprintf($error_code[2012],$v['name']),2012);

                        if ( !preg_match('/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/', @$formdata[$k]) )
                            throw new Exception(sprintf($error_code[2012],$v['name']),2012);
                    }
                    // 验证数字
                    else if($regular == 'digit')
                    {
                        if (!ctype_digit(@$formdata[$k]))
                        {
                            throw new Exception(sprintf($error_code[2004],$v['name']),2004);
                        }
                    }
                    // 验证数字包括0
                    else if($regular == 'number')
                    {
                        if (!is_numeric(@$formdata[$k]))
                        {
                            throw new Exception(sprintf($error_code[2012],$v['name']),2013);
                        }
                    }

                    // 验证浮点数
                    else if($regular == 'float')
                    {
                        $formdata[$k] = (float) $formdata[$k];
                    }

                    else if($regular == '2int')
                    {
                        if(isset($formdata[$k]))
                        {
                            $formdata[$k] = (int) $formdata[$k];
                        }
                        else
                        {
                            $formdata[$k] = 0;
                        }
                    }

                    //数字范围
                    else if(stristr($regular,'range'))
                    {
                        preg_match('/(\d+|\*)-(\d+|\*)/', $regular, $matches);
                        if( !@$matches[0] ) throw new Exception($error_code[2007],2007);

                        $size = explode('-',$matches[0]);
                        if ( isset($size[0]) && isset($size[1]) )
                        {
                            $min = $size[0];
                            $max = $size[1];
                        }
                        else
                        {
                            throw new Exception($error_code[2007],2007);
                        }

                        if($formdata[$k] < $min || $formdata[$k] > $max)
                        {
                            throw new Exception("{$v['name']}取值范围在{$min}-{$max}",$code);
                        }
                    }

                    //是否为日期
                    else if($regular == 'date')
                    {
                        if($formdata[$k] != date('Y-m-d',strtotime($formdata[$k])))
                        {
                            throw new Exception(sprintf($error_code[2007],$v['name']),2007);
                        }
                    }

                    else if($regular == 'datetime')
                    {
                        if($formdata[$k] != date('Y-m-d H:i',strtotime(@$formdata[$k])))
                        {
                            throw new Exception(sprintf($error_code[2006],$v['name']),2006);
                        }
                    }
                    
                    else if($regular == 'password')
                    {
                        if (!preg_match('/^([0-9a-zA-Z]+)$/', @$formdata[$k]))
                        {
                            throw new Exception(sprintf($error_code[2011],$v['name']),2011);
                        }
                    }
                    else if(stristr($regular,'array'))
                    {
                        if(!in_array($formdata[$k],$regular))
                        {
                            throw new Exception(sprintf($error_code[2005],$v['name']),2005);
                        }
                    }
                    else if($regular == 'function')
                    {
                        $return = call_user_func_array($v['fname'],array(&$formdata[$k]));

                        if(!$return)
                        {
                            throw new Exception(sprintf($error_code[2004],$v['name']),2004);
                        }
                    }

                }

                $checkedData[$k] = $formdata[$k];
            }

            return $checkedData;
        }
        else
        {
            throw new Exception($error_code[2002],2002);
        }
    }

}
